package inventory.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import inventory.common.CommonConstants;
import inventory.common.ResultData;
import inventory.entity.*;
import inventory.entity.po.SaleRequestPo;
import inventory.service.*;
import inventory.utils.SelectingCondition;
import inventory.utils.SelectingMapGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author sxt
 * @create 2019-12-01 16:31
 */
@Api(tags = {"物料销库"}, value = "物料消除库存相关接口")
@RestController
@RequestMapping(CommonConstants.ELIINVENTORY_PREFIX)
public class EliminateInventoryController {


    @Autowired
    private EquipmentService equipmentService;

    @Autowired
    private TerminalService terminalService;

    @Autowired
    private MaterialStuffService stuffService;


    @RequestMapping(value = "/eliminateInventory", method = RequestMethod.POST)
    public ResultData eliminateInventory(@RequestBody List<String> saleIds) {

        List<SaleRequest> saleRequests = saleRequestService.selectList(new EntityWrapper<SaleRequest>().in("sale_id", saleIds));

        ArrayList<MaterialStuff> rs = new ArrayList<>();

        for (SaleRequest s : saleRequests) {
            Integer type = s.getSaleType();
            if (type == 1) {//销库终端
                String serialNum = s.getSerialNum();
                Terminal t = terminalService.selectOne(new EntityWrapper<Terminal>().eq("IMEI", serialNum));
                t.setStatus(1);//置1表示销库
                t.setSaleTime(new Date());
                t.updateById();//更新到数据库

                s.setStatus(1);
                s.updateById();

            } else if (type == 2) {//销库设备

                String serialNum = s.getSerialNum();
                Equipment equipment = equipmentService.selectOne(new EntityWrapper<Equipment>().eq("IMEI", serialNum));
                equipment.setStatus(1);//置1表示销库
                equipment.setStorageTime(new Date());
                equipment.updateById();//更新到数据库

                s.setStatus(1);
                s.updateById();

            } else if (type == 3) {//更新物料使用量信息


                String stuffId = s.getStuff_id();
                MaterialStuff materialStuff = stuffService.selectOne(new EntityWrapper<MaterialStuff>().eq("stuff_id", stuffId));
                Long usedCount = s.getNum();
                Long oldCount = materialStuff.getInRepository();
                Long newLeftCount = oldCount - usedCount;
                if (newLeftCount < 0) {//如果总量不足，不给予物料使用量变更，并记录下该物料的信息，返回给前端
                    rs.add(materialStuff);
                } else if (newLeftCount > 0) {//如果总量充足，则给予物料使用量变更
                    materialStuff.setOutRepository(materialStuff.getOutRepository() + usedCount);
                    materialStuff.setInRepository(newLeftCount);
                    materialStuff.updateById();
                }
                s.setStatus(1);
                s.updateById();


            }

        }

        if (!(rs.size() > 0)){
            return new ResultData().OK().setResultIns("销库成功");

        }else {
            return new ResultData().OK()
                    .setResultIns("销库操作已经完成，返回的数据集合：表示销库时，总量小于使用量的所有物料信息集合，这些物料信息将不会在数据库中更新")
                    .setObjs(rs);
        }


    }

    @Autowired
    private SaleRequestService saleRequestService;


    @Autowired
    private RoleService roleService;


    @RequestMapping(value = "/addEliminateRequest", method = RequestMethod.POST)
    public ResultData addEliminateRequest(@RequestBody(required = true) List<SaleRequest> saleRequests, String managerId) {


        if (managerId == null) {
            return new ResultData().FAILD().setResultIns("managerId不能为空");
        }

        Role pid = roleService.selectOne(new EntityWrapper<Role>().eq("pid", managerId));
        if (pid == null) {
            return new ResultData().FAILD().setResultIns("managerId查询失败,你的市级呢？");
        } else {
            for (SaleRequest s : saleRequests) {
                s.setRoleId(pid.getRoleId());//设置市级role_id
            }
        }


        List<SaleRequest> rs = saleRequestService.addSaleRequest(saleRequests);
        if (rs.size() > 0) {
            return new ResultData().FAILD().setObjs(rs).setResultIns("全部或部分物料销库请求失败，原因很可能是：相关物料未在仓库中找到或该物料已经存在相关的销库请求 | 在进行相关物料库存追加时储量不足");
        }
        return new ResultData().OK();
    }

    @RequestMapping(value = "/getEliminateRequests", method = RequestMethod.GET)
    public ResultData getEliminateRequests(String roleId) {
        List<SaleRequestPo> saleRequests = saleRequestService.querySaleRequestByRoleId(roleId);
        return new ResultData().OK().setObjs(saleRequests);
    }

    @RequestMapping(value = "/getSelfEliminateRequests", method = RequestMethod.GET)
    public ResultData getSelfEliminateRequests(String userId) {
        List<SaleRequestPo> saleRequests = saleRequestService.querySaleRequestByUserId(userId);
        return new ResultData().OK().setObjs(saleRequests);
    }

    @RequestMapping(value = "cancelEliminateRequest", method = RequestMethod.GET)
    public ResultData cancelEliminateRequest(String saleId) {
        boolean rs = saleRequestService.deleteById(saleId);
        if (rs) {
            return new ResultData().OK().setResultIns("销库请求撤销成功");
        } else {
            return new ResultData().FAILD().setResultIns("销库请求撤销失败");
        }
    }


    /**
     * 根据条件查询出销库请求记录（可变条件）
     *
     * @param condition
     * @return
     */
    @ApiOperation(value = "根据条件查询出销库请求记录（可变条件）")
    @RequestMapping(value = "/getSaleRequestsByCondition", method = RequestMethod.POST)
    public ResultData getSaleRequestsByCondition(SelectingCondition.SaleRrequestCondition condition) {
        if (StringUtils.isEmpty(condition.getRoleId())) {
            return new ResultData().FAILD().setResultIns("需要roleId字段来查询出入库记录");
        }
        SelectingMapGenerator<SaleRequest> mapGenerator = new SelectingMapGenerator<SaleRequest>(SaleRequest.class, condition);
        Map resultQueryConditionMap = mapGenerator.getResultQueryConditionMap();
        if (resultQueryConditionMap.isEmpty()) {
            return new ResultData().FAILD().setResultIns("未检测到任何有效匹配条件");
        }
        List<SaleRequest> saleRequests = saleRequestService.querySaleRequestsByCondition(resultQueryConditionMap);
        return new ResultData().OK().setObjs(saleRequests);
    }


}
